package com.coffee.common.util;

import com.coffee.common.config.MinioConfig;
import com.coffee.common.exception.CustomException;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;

/**
 * Minio工具类
 *
 * @author Kevin
 */
@Component
@Slf4j
public class MinioUtil {

    @Resource
    MinioConfig minioConfig;

    @Resource
    MinioClient minioClient;

    @Bean
    private MinioClient minioClient() {
        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioConfig.getEndpoint())
                .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                .build();
        return minioClient;
    }

    public String uploadObject(InputStream stream, String filepath) {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConfig.getBucketName()).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConfig.getBucketName()).build());
            }
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(filepath.substring(1))
                    .contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE)
                    .stream(stream, stream.available(), -1).build();
            minioClient.putObject(putObjectArgs);
        } catch (Exception e) {
            log.error("上传文件失败，{}", e.getMessage());
            throw new CustomException("上传文件失败，" + e.getMessage());
        }
        return minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + filepath;
    }

}
